__version__ = "$Revision: 120 $"
__date__ = "$Date: 2011-07-31 16:47:57 +0200 (So, 31 Jul 2011) $"
__lastChangedBy__ = "$Author: wolters@3sconsult.de $"
__repository__ = "$HeadURL: https://sir3spy.googlecode.com/svn/Sir3sPy/Utils/trunk/DbOraUtest.py $"

"""Class OpcClient's UnitTest.
"""

import os
import sys
import logging
import unittest
import re
import time
import win32com.client

# makepy -i:
# Windows Script Host Object Model (1.0)
# {F935DC20-1CF0-11D0-ADB9-00C04FD58A0B}, lcid=0, major=1, minor=0
from win32com.client import gencache
gencache.EnsureModule('{F935DC20-1CF0-11D0-ADB9-00C04FD58A0B}', 0, 1, 0)

# makepy -i:
# Matrikon OPC Automation 2.0 (1.0)
# {F8582D24-88FB-11D0-B850-00C0F0104305}, lcid=0, major=1, minor=0
from win32com.client import gencache
gencache.EnsureModule('{F8582D24-88FB-11D0-B850-00C0F0104305}', 0, 1, 0)

from Opc import OpcClient
                      
class test_OpcClient(unittest.TestCase):
    """
    """
 
    def setUp(self):
        """
        """      

        fileName =__file__
        logName=fileName[__file__.find('Sir3sPy'):]+'.'+self.__class__.__name__+'.setUp'
        logName=logName.replace('.py','').replace('\\','.').replace('/','.')  
        logger = logging.getLogger(logName)    
        
        logger.debug('Start')          
        
        # OPC server start
        self.shell = win32com.client.Dispatch("WScript.Shell")
        self.process = self.shell.Exec('"C:\Program Files (x86)\Common Files\MatrikonOPC\Common\PSTCFG.exe" PSTCFGMatrikon.OPC.Simulation.1 MATRIKON.OPC')
        time.sleep(3)
        self.shell.SendKeys('^n') 
        time.sleep(3)
        self.shell.SendKeys('{ENTER}') 
        time.sleep(3)        
        self.shell.SendKeys('^o') 
        time.sleep(3)  
        self.shell.SendKeys('{ENTER}') 
        time.sleep(3)                     
        self.shell.SendKeys('MatrikonSimulationServerOpcTest.xml') 
        self.shell.SendKeys('{ENTER}') 
        time.sleep(3)

        # OPC client to test                
        self.opc=OpcClient()
        self.opc.connect()
        
        logger.debug('_Done')   
             
    def tearDown(self):
        """
        """        

        fileName =__file__
        logName=fileName[__file__.find('Sir3sPy'):]+'.'+self.__class__.__name__+'.tearDown'
        logName=logName.replace('.py','').replace('\\','.').replace('/','.')  
        logger = logging.getLogger(logName)    
        
        logger.debug('Start')         
                
        self.opc.disconnect()     
        
        # OPC server stop
        self.shell.SendKeys('^n')         
        time.sleep(3)
        self.shell.SendKeys('{ENTER}') 
        time.sleep(3)                
        self.process.Terminate()
        time.sleep(3)  

        logger.debug('_Done')   

    def test_(self):
        """        
        """  

        fileName =__file__
        logName=fileName[__file__.find('Sir3sPy'):]+'.'+self.__class__.__name__+'.test_'
        logName=logName.replace('.py','').replace('\\','.').replace('/','.')  
        logger = logging.getLogger(logName)         
                           
        (item, writestatus) = self.opc.writeItems([('Actor.aActor',666)])[0]
        self.assertEqual(writestatus,'Success')   

        (item, value, quality, timestamp) = self.opc.readItems(['Actor.aActor'])[0]
        self.assertEqual(value,666)  
    
        items=['Actor.aActor','Sensor.aSensor']
        itemvaluepairs=[('Actor.aActor',123),('Sensor.aSensor',123)]
        
        for (item, writestatus) in self.opc.writeItems(itemvaluepairs):
            self.assertEqual(writestatus,'Success')  
            
        for (item, value, quality, timestamp) in self.opc.readItems(items):
            self.assertEqual(value,123)            
                                               
if __name__ == "__main__":

    # logging configuration
    filename=__file__
    loggerName=filename[__file__.find('Sir3sPy'):].replace('.py','').replace('\\','.').replace('/','.')
    logging.getLogger(loggerName).addHandler(logging.NullHandler())
    # configure logfile
    moduleName,ext=os.path.splitext(os.path.basename(__file__))     
    logFileName = os.path.join(os.getcwd(),moduleName+'.log') 
    # configure logging       
    logging.basicConfig(filename=logFileName,filemode='w',level=logging.DEBUG,format="%(asctime)s ; %(name)-60s ; %(levelname)-7s ; %(message)s")        

    try:    
        logger = logging.getLogger(loggerName)
        
        #test
        testClassNamesRegEx = re.compile("test_")
        testClassNames = filter(testClassNamesRegEx.search,dir())        
        testClassNamesDotted = [moduleName+'.'+testClassName for testClassName in testClassNames]
        loader = unittest.TestLoader()
        suite = loader.loadTestsFromNames(testClassNamesDotted)
        unittest.TextTestRunner(verbosity=2).run(suite)
        
        sys.exit(0) 
        
    except SystemExit:        
        pass    
    except:
        logger.error('Exception.') 
    finally:                                         
        sys.exit(0)                        
